package com.easpeed.comon.database

import android.util.Log;
import com.bigyu.utils.Logger
import com.blankj.utilcode.util.TimeUtils
import com.easpeed.comon.database.bean.CommonDataSqlBean
import com.easpeed.comon.database.bean.CrashBean
import com.easpeed.comon.database.bean.JourBean

/**
 * Created by bigyu on 2024/12/6 19:04
 * com.easpeed.comon.database
 */
object DataBaseUtils {

    const val TAG = "DataBaseUtils"

    private fun loge(tag: String = TAG, msg: String?) {
        Logger.e(tag, "$msg")
    }


    @JvmStatic
    fun saveSingleDataByType(dataType: String, bean: CommonDataSqlBean) {
        val dao = DataBaseCommon.getInstance().getCommonDataDao()
        dao?.apply {
            bean.dataType = dataType
            val list = this.queryList(dataType)
            val sqlData = list?.firstOrNull()
            if (sqlData == null) {
                this.insert(bean)
                loge(msg = "插入数据成功: $bean")
            } else {
                bean.updateTimeMills = System.currentTimeMillis()
                val result = this.update(bean)
                loge(msg = "更新数据成功: $result   $bean")
            }
        }
    }

    @JvmStatic
    fun saveDataByType(dataType: String, bean: CommonDataSqlBean) {
        val dao = DataBaseCommon.getInstance().getCommonDataDao()
        dao?.apply {
            bean.dataType = dataType
            this.insert(bean)
            loge(msg = "插入数据成功: $bean")
        }
    }


    fun querySingleDataByType(dataType: String): CommonDataSqlBean? {
        val dao = DataBaseCommon.getInstance().getCommonDataDao()
        return dao?.queryList(dataType)?.firstOrNull()
    }

    @JvmStatic
    fun queryDataByType(dataType: String): List<CommonDataSqlBean>? {
        val dao = DataBaseCommon.getInstance().getCommonDataDao()
        return dao?.queryList(dataType)
    }


    /**
     * 保存崩溃日志
     */
    public fun saveCrashLog(type: String?, content: String?) {
        Thread {
            try {
                val dao = DataBaseCommon.getInstance().getCrashDao()
                val maxLength = 1048576 // 1MB
                val safeContent = if (content != null && content.length > maxLength) {
                    content.substring(0, maxLength)
                } else {
                    content
                }
                dao?.insert(CrashBean(type, safeContent))
                Logger.e("DataBaseUtils", "数据插入成功=>size=${content?.length}")
            } catch (e: Exception) {
                e.printStackTrace()
            }
            //顺便删除10天前的数据
            delete10DayCrashLog()
        }.start()
    }

    /**
     * 获取崩溃日志
     * @param timeSecond 时间戳（s）
     */
    fun queryCrashLog(
        timeSecond: Long,
        interfaces: () -> CrashBeanResultInterface?,
    ) {
        Thread {
            try {
                val dao = DataBaseCommon.getInstance().getCrashDao()
                //崩溃日志
                val crashList = dao?.queryCrashList(checkMills(timeSecond)).apply {
                    this?.forEach {
                        it.init()
                    }
                }

                val jourBean = JourBean(
                    crashList
                )

                Logger.e(
                    "DataBaseUtils",
                    "查询崩溃日志数据${mills2String(checkMills(timeSecond) * 1000)}成功=>${crashList?.size}条"
                )
                interfaces.invoke()?.result(jourBean)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            //顺便删除10天前的数据
            delete10DayCrashLog()

        }.start()
    }

    /**
     * 删除10天前的崩溃日志
     * @param timeSecond 时间戳（s）
     */
    fun delete10DayCrashLog() {
        val time = System.currentTimeMillis() - 10 * 24 * 60 * 60 * 1000
        deleteCrashLog(time)
    }

    /**
     * 删除崩溃日志
     * @param timeSecond 时间戳（s）
     */
    fun deleteCrashLog(timeSecond: Long) {
        Thread {
            val dao = DataBaseCommon.getInstance().getCrashDao()
            val crashList = dao?.deleteCrash(checkMills(timeSecond))
            Logger.e(
                "DataBaseUtils",
                "删除数据${mills2String(checkMills(timeSecond) * 1000)}成功=>${crashList}条"
            )
        }.start()
    }

    private fun mills2String(mills: Long): String? {
        return TimeUtils.millis2String(mills)
    }

    private fun checkMills(time: Long): Long {
        if ("$time".length == 13) {
            return time / 1000
        }
        return time
    }
}